
package session.stateless;

import entity.Address;
import entity.Employee;
import entity.Customer;
import entity.Inquiry;
import entity.Job;
import entity.Product;
import entity.PurchaseItem;
import entity.PurchaseOrder;
import entity.Quotation;
import entity.QuotationItem;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class JobSessionBean implements JobSessionBeanLocal, JobSessionBeanRemote {
    
    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public Job getJob (PurchaseItem poi)
    {
        ArrayList <Job> jobs = getJobs();
        for (Job j: jobs )
        {
            for (PurchaseItem purchaseItem: j.getPurchaseOrder().getPurchaseItems())
            {
                if (purchaseItem.getId().compareTo(poi.getId())==0)
                    return j;
            }
        }
        return null;
    }
    
    @Override
    public void addJob(Long custId, String userId, List<Quotation> quotations, Timestamp jobDate, Long selectedQuotationId, String description, String type) {
        Customer customer = entityManager.find(Customer.class, custId);
        Employee employee = null;
        if (userId != null) {
            employee = entityManager.find(Employee.class, userId);
        }
        ArrayList qs = new ArrayList<Quotation>();
        if (quotations != null) {
            for (Quotation q : quotations) {
                if (q.getInquiry() != null) {
                    Inquiry i = entityManager.find(Inquiry.class, q.getInquiry().getId());
                    q.setInquiry(i);
                } else {
                    q.setInquiry(null);
                }

                List qis = new ArrayList<QuotationItem>();
                for (QuotationItem qi : q.getQuotationItems()) {
                    Product temp2 = entityManager.find(Product.class, qi.getProduct().getCode());
                    qi.setProduct(temp2);

                    Address temp3 = null;
                    if (qi.getShippingAddress() != null) {
                        temp3 = entityManager.find(Address.class, qi.getShippingAddress().getId());
                        qi.setShippingAddress(temp3);
                    } else {
                        qi.setShippingAddress(null);
                    }

                    qis.add(qi);
                }
                q.setQuotationItems(qis);

                qs.add(q);
            }
        }

        Quotation q = null;
        if (selectedQuotationId != null) {
            q = entityManager.find(Quotation.class, selectedQuotationId);
        }
        Job job = new Job(customer, employee, qs, jobDate, q, description, type, null);
        entityManager.persist(job);
        entityManager.flush();
    }

    @Override
    public ArrayList<Quotation> getQuotations() {
        ArrayList<Quotation> q = new ArrayList<Quotation>();
        for (Job j : getJobs()) {
            for (Quotation c : j.getQuotations()) {
                q.add(c);
            }
        }
        HashSet set = new HashSet(q);
        q.clear();
        q.addAll(set);
        return q;
    }

    @Override
    public Job getJob(Long jobId) {
        Job job = entityManager.find(Job.class, jobId);
        return job;
    }

    @Override
    public ArrayList<Job> getJobs(String userId, Boolean processing) {
        Query query = entityManager.createQuery("SELECT u FROM Job u");

        ArrayList<Job> jobs = new ArrayList<Job>();
        for (Object o : query.getResultList()) {
            if (processing) { //jobs not sent for credit check yet
                if (((Job) o).getEmployee().getUserId().compareTo(userId) == 0 && ((Job) o).getSelectedQuotation() == null) {

                    jobs.add((Job) o);
                }
            } else { //job sent for credit check, ATP check or manager approval
                if (((Job) o).getEmployee().getUserId().compareTo(userId) == 0 && ((Job) o).getSelectedQuotation() != null) {
                    jobs.add((Job) o);
                }
            }

        }
        return jobs;

    }

    @Override
    public ArrayList<Job> getJobs() {
        Query query = entityManager.createQuery("SELECT u FROM Job u");
        ArrayList<Job> jobs = new ArrayList<Job>();
        for (Object o : query.getResultList()) {
            Job job = (Job) o;
            jobs.add(job);
        }
        return jobs;
    }

    @Override
    public void updateJob(Long jobId, Long custId, String userId, List<Quotation> quotations, Timestamp jobDate,
            Long selectedQuotationId, String description, String type, Long purchaseOrderId) {
        Job job = entityManager.find(Job.class, jobId);
        Customer customer = entityManager.find(Customer.class, custId);
        Employee employee = entityManager.find(Employee.class, userId);
        List<Quotation> qs = new ArrayList<Quotation>();
        for (Object o : quotations) {
            Quotation q = entityManager.find(Quotation.class, ((Quotation) o).getId());
            qs.add(q);
        }
        job.setCustomer(customer);
        job.setEmployee(employee);
        job.setQuotations(qs);
        job.setJobDate(jobDate);
        Quotation q = null;
        if (selectedQuotationId != null) {
            q = entityManager.find(Quotation.class, selectedQuotationId);
        }

        job.setSelectedQuotation(q);
        job.setDescription(description);
        job.setType(type);

        if (purchaseOrderId != null) {
            PurchaseOrder purchaseOrder = entityManager.find(PurchaseOrder.class, purchaseOrderId);
            job.setPurchaseOrder(purchaseOrder);
        }
        entityManager.persist(job);
        entityManager.flush();
    }

    @Override
    public void completeJob(String jobId, Long selectedQuotationId) {
        Job job = entityManager.find(Job.class, jobId);
        Quotation q = entityManager.find(Quotation.class, selectedQuotationId);
        job.setSelectedQuotation(q);
        for (Object o : job.getQuotations()) {
            if (((Quotation) o).getId() != selectedQuotationId) {
                ((Quotation) o).setStatus("Expired");
            } else {
                ((Quotation) o).setStatus("Converted");
            }
        }
    }

    @Override
    public void updateQuotation(Long id, QuotationItem qi) {
        try {
            Quotation q = entityManager.find(Quotation.class, id);
            List<QuotationItem> quotationItems = q.getQuotationItems();

            Address temp = entityManager.find(Address.class, qi.getShippingAddress().getId());
            qi.setShippingAddress(temp);

            Product temp2 = entityManager.find(Product.class, qi.getProduct().getCode());
            qi.setProduct(temp2);

            quotationItems.add(qi);
            q.setQuotationItems(quotationItems);

            entityManager.persist(q);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public Quotation getQuotation(Long id) {
        Quotation q = entityManager.find(Quotation.class, id);

        return q;
    }

    @Override
    public QuotationItem getQuotationItem(Long id) {
        QuotationItem qi = entityManager.find(QuotationItem.class, id);

        return qi;
    }

    @Override
    public void updateJob(Long id, Quotation q) {
        try {
            Job j = entityManager.find(Job.class, id);

            List<Quotation> quotations = j.getQuotations();

            for (Quotation temp : quotations) { //expire all quotations before adding the new one
                temp.setStatus("Expired");

                entityManager.persist(temp);
                entityManager.flush();
            }
            
            
          //  Quotation quotation = entityManager.find(Quotation.class, q.getId());
            //System.out.println(quotation + "Object");
//            quotations.add(quotation);

//            j.setQuotations(quotations);
            System.out.println(j.getQuotations().size() + "quot size");
            Quotation quotation = new Quotation ();
            j.getQuotations().add(quotation);
           
            entityManager.persist(j);
            System.out.println(j.getQuotations().size() + "quot size 2");
            entityManager.flush();
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
    }

    @Override
    public void updateQuotation(Long id, double quotationTotalAmount, double quotationSubTotal, double quotationTotalShipping, String remark) {
        Quotation temp = getQuotation(id);

        temp.setTotalAmount(quotationTotalAmount);
        temp.setSubTotal(quotationSubTotal);
        temp.setTotalShipping(quotationTotalShipping);
        entityManager.persist(temp);
        entityManager.flush();
    }

    @Override
    public void updateQuotation(Long id, String remark) {
        Quotation temp = getQuotation(id);

        temp.setRemark(remark);

        entityManager.persist(temp);
    }

    @Override
    public void deleteQuotationItem(Long quotationId, Long quotationItemId) {
        Quotation temp = getQuotation(quotationId);
        QuotationItem temp2 = entityManager.find(QuotationItem.class, quotationItemId);

        temp.getQuotationItems().remove(temp2);

        entityManager.persist(temp);

        entityManager.remove(temp2);
    }

    @Override
    public void updatePurchaseOrder(Long id, Long purchaseOrderId) {
        Job job = entityManager.find(Job.class, id);
        PurchaseOrder po = entityManager.find(PurchaseOrder.class, purchaseOrderId);
        job.setPurchaseOrder(po);
        entityManager.persist(job);
        entityManager.flush();

    }

    @Override
    public void rejectPurchaseOrder(Long jobId) {
        Job job = entityManager.find(Job.class, jobId);
        job.setPurchaseOrder(null);
        job.setSelectedQuotation(null);
        entityManager.persist(job);
        entityManager.flush();
    }
}
